package com.yunc.modules.sys.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.common.utils.R;
import com.yunc.modules.sys.entity.SysMailRetrieve;
import com.yunc.modules.sys.entity.SysUser;
import com.yunc.modules.sys.mapper.SysMailRetrieveMapper;
import com.yunc.modules.sys.service.ISysMailRetrieveService;
import com.yunc.modules.sys.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;

/**
 * 邮件找回密码表 service实现
 *
 * @author concong tao
 * @since 2019-02-05
 */
@Service
public class SysMailRetrieveServiceImpl extends ServiceImpl<SysMailRetrieveMapper, SysMailRetrieve> implements ISysMailRetrieveService {


    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysMailRetrieveMapper sysMailRetrieveMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R saveMailRetrieve(String basePath, String loginName) {
        List<SysUser> userList = sysUserService.list(new QueryWrapper<SysUser>().eq("login_name", loginName));
        if (userList == null || userList.size() == 0) {
            return R.error("未查询到该用户");
        }
        SysUser sysUser = userList.get(0);
        if (StringUtils.isEmpty(sysUser.getMail())) {
            return R.error("您的账号未绑定邮箱,无法重置密码");
        }
        // 重置邮箱
        MimeMessage message = mailSender.createMimeMessage();
        // 生成,30分钟后过期
        // Timestamp outDate = new Timestamp(System.currentTimeMillis() + (long)(30*60*1000));
        long outtimes = System.currentTimeMillis() + (long)(30*60*1000);
        String sid = loginName + "&" + RandomUtil.randomString(6) + "&" + outtimes;
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("90taocongcong@163.com");
            helper.setTo(sysUser.getMail());
            helper.setSubject("主题：重置密码");
            String url = basePath + "index.html#/sys/user/sysUserResetPassword/sid=" + DigestUtil.md5Hex(sid) + "/userId=" + sysUser.getId();
            String emailContent = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href=" + url +" target='_BLANK'>点击我重新设置密码</a>" +
                    "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'";
            helper.setText(emailContent, true);
            mailSender.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
        SysMailRetrieve mailRetrieve = new SysMailRetrieve();
        mailRetrieve.setUserId(sysUser.getId());
        mailRetrieve.setSid(DigestUtil.md5Hex(sid));
        mailRetrieve.setOutTime(new Date(outtimes));
        this.save(mailRetrieve);
        return R.ok("操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码");
    }

    @Override
    public R verifyUrl(Long userId, String sid) {
        if (userId == null || StringUtils.isEmpty(sid)) {
            return R.error("链接错误");
        }
        // 查出最新的邮件
        SysMailRetrieve mailRetrieve = sysMailRetrieveMapper.getLastMailRetrieve(userId);
        if (mailRetrieve == null) {
            return R.error("未查询到重置信息");
        }
        if (mailRetrieve.getOutTime().getTime() <= System.currentTimeMillis()) {
            return R.error("链接已经过期,请重新申请找回密码.");
        }
        if (!StringUtils.equals(sid, mailRetrieve.getSid())) {
            return R.error("参数错误,请重新申请找回密码.");
        }
        return R.ok();
    }
}
